import React from 'react';
import ReactDOM from 'react-dom';
import './detail.scss';
class NowAuction extends React.Component {
  constructor(props) {
    super(props);
    // 出价框初始值
    this.state = {
      priceInput: -1,
      currentPrice: 0,
      isCalling:0,
      personInfo: [],
      timer:-1,
      timerId:0,
      isEnd:0,
      remain:0,
      progressTimer:0
    };
    this.handlePriceInput = this.handlePriceInput.bind(this);
    this.handleBtnAdd = this.handleBtnAdd.bind(this);
    this.handleBtnSub = this.handleBtnSub.bind(this);
    this.loadAuctionInfo = this.loadAuctionInfo.bind(this);
    this.callPrice = this.callPrice.bind(this);
    this.progress = this.progress.bind(this);
    this.initProgress = this.initProgress.bind(this);
  }
  // 输入框出价数值变化时触发
  handlePriceInput(e) {
    // console.log(123);
    this.setState({priceInput: e.target.value});
  }
  // 加价按钮事件
  handleBtnAdd(e) {
    let num = this.props.item.b_step;
    let addNum = this.state.priceInput*1 + num * 1;
    this.setState({priceInput: addNum});
  }
  // 减价按钮事件
  handleBtnSub(e) {
    let num = this.props.item.b_step;
    let subNum = (this.state.priceInput*1 - num * 1) > 0  ? (this.state.priceInput*1 - num * 1)  : this.state.priceInput*1;
    this.setState({priceInput: subNum});
  }

  progress(timeleft, timetotal, $element) {
    let that = this;
    // if(this.stopProgress){
    //   //停止倒计时
    //   if(this.state.progressTimer){
    //     clearTimeout(this.state.progressTimer);
    //     this.setState({progressTimer:0});
    //   }
    //   return;
    // }
    console.log('timer:'+this.state.progressTimer,timeleft);
    var progressBarWidth = timeleft * $element.width() / timetotal;
    $element.find('div').animate({
      width: progressBarWidth
    }, 500).html();
    // if (timeleft > 0) {
    //   this.setState({progressTimer:setTimeout(function() {
    //     this.progress(timeleft - 1, timetotal, $element);
    //   }.bind(this), 1000)});
    // }
  }

  initProgress($element){
    $element.find('div').css("width",$element.width());
    clearInterval(this.state.progressTimer);
  }

  // 获取拍卖信息
  loadAuctionInfo() {
    let that = this;
    $.ajax({
      type: 'GET',
      url: CBH.apiRoot + '/?g=Api&m=CommonProduct&a=callback_info',
      dataType: 'jsonp',
      data: {
        cpid: this.props.item.id
      },
      success: function(res) {
        //{"status":1,"data":{"cpid":6,"start_time":1482890400,"end_time":1482908400,"uid":"1019","current_price":25000,"stime":1482897612},"item":[{"uid":"1019","price":25000,"cpid":6,"ctime":1482896473,"nickname":"\u6469\u6258\u8ff7","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/qH1PgyPjFvYE8ka9x32sPibXLfvqUys9VmW8ZzRmiaM88MuugAvciczpORicicudRfL2L8m7sx7KkZfGx5jkxSWibwYpJPOYibicRcYg\/0"},...],"referer":"","state":"success"}
        //{"status":0,"data":{"current_price":"20000","cpid":"5","start_time":"1517371200","auction_status":"0"},"msg":"\u62cd\u5356\u672a\u5f00\u59cb\uff01\u8bf7\u5237\u65b0\u91cd\u8bd5!","referer":"","state":"fail"}
        //auction_status 0 未开拍 1 拍卖中 2流拍 3成交
        if(res.status){
            this.setState({
              personInfo:res.item,
              currentPrice:res.data.current_price*1,
              remain:res.data.end_time-res.data.stime
            });

            this.setState({endTime:res.data.end_time});
            if(this.state.remain <= this.props.item.countdown*1){
              clearInterval(this.state.progressTimer);
              this.setState({
                progressTimer:setInterval(function(){
                  if(this.state.remain>0){
                    this.progress(this.state.remain, this.props.item.countdown*1, $('#progressBar'));
                    }
                }.bind(this),1000)
              });
            }else{
              this.initProgress($('#progressBar'));
            };

            if(this.state.timer || this.state.timer==-1){
              clearInterval(this.state.timer);
              this.setState({timer:setInterval(function(){
                if(this.state.remain*1-1>0){
                  this.setState({remain:(this.state.remain*1-1)});
                }
                else{
                  clearInterval(this.state.timer);
                }
              }.bind(this),1000)})
            }
        }else{
          //否开拍状态
          if(res.data.auction_status=="2"||res.data.auction_status=="3"){
            clearInterval(this.state.timerId);
            window.location.reload(true);
          }
        }
      }.bind(this)
    });
  }

  // countDown(){
  //   this.setState({timeCount:this.formatTime()});
  // }
  //倒计时格式化
 formatTime(timescale) {
	//转化为 日+小时+分+秒
	var time = parseFloat(timescale);
	if (time != null && time != ""){
		if (time < 60) {
			var s = time;
			time = s + '秒';
		} else if (time > 60 && time < 3600) {
			var m = parseInt(time / 60);
			var s = parseInt(time % 60);
			time = m + "分钟" + s + "秒";
		} else if (time >= 3600 && time < 86400) {
			var h = parseInt(time / 3600);
			var m = parseInt(time % 3600 / 60);
			var s = parseInt(time % 3600 % 60 % 60);
			time = h + "小时" + m + "分钟" + s + "秒";
		} else if (time >= 86400) {
			var d = parseInt(time / 86400);
			var h = parseInt(time % 86400 / 3600);
			var m = parseInt(time % 86400 % 3600 / 60)
			var s = parseInt(time % 86400 % 3600 % 60 % 60);
			time = d + '天' + h + "小时" + m + "分钟" + s + "秒";
		}
	}
	return time;
}
  // 点击出价按钮调用
  callPrice() {

    $.ajax({
      type: 'GET',
      url: CBH.apiRoot + '/?g=Api&m=CommonProduct&a=call_price',
      dataType: 'jsonp',
      data: {
        uid: CBH.UserInfo.id,
        price: this.state.priceInput*1+this.state.currentPrice*1,
        cpid: this.props.item.id
      },
      success: function(res) {
        //{status: 0, msg: "拍卖已结束！2", referer: "", state: "fail"}
        //status 1 出价成功提交
        switch (res.status) {
          case 0:
            alert(res.msg);
            this.loadAuctionInfo();
            break;
          case 1:
            alert(res.msg);
            this.loadAuctionInfo();
            break;
          default:
          //  console.log(res.status);
            //console.log('default');
        }
        //console.log(res);

      }.bind(this)
    });
  }
  componentWillReceiveProps(nextProps){
    //console.log('nextProps');
  }
  componentDidMount() {

  }

  componentDidUpdate(nextProps, nextState){
    if(this.props.item.id && this.props.item.auction_status =="1" && !nextProps.item.id){//this.state.priceInput == -1
      this.setState({priceInput:(this.props.item.b_step|0)});
      this.loadAuctionInfo();
      this.setState({timerId:setInterval(this.loadAuctionInfo, 5000)});
    }
  }

  componentWillUnmount(){
    clearInterval(this.state.timerId);
  }
  render() {
    const {priceInput, currentPrice, remain} = this.state;
    let isfirstUser=1,
    CallUserList = this.state.personInfo.map((p) => {
      if(isfirstUser){
        isfirstUser=0;
        return (
          <div className='avatar top-member'>
            <img className="img-responsive crown" src={'../img/crown.png'} alt="crown"/>
            <img className="img-responsive" src={ p.headimgurl } alt={ p.nickname } />
            <p>{ p.nickname.replace(/^(.)(?:.+)(.)$/, "$1**$2") }</p>
          </div>
        )
      }
      else{
        return (
        <div className="avatar gray">
          <img className="img-responsive" src={ p.headimgurl } alt={ p.nickname } />
          <p>{ p.nickname.replace(/^(.)(?:.+)(.)$/, "$1**$2") }</p>
        </div>
      );
      }
    });
    let startTime = new Date();
    startTime.setTime(this.props.item.start_time*1000);
    const readyAuction = (
      <div className="col-xs-12">
        <div className="time">
          <p className="now-auctioning-title">暂未开拍</p>
        </div>

        <div className="readyAuction">
          <p>拍品将于{startTime.getFullYear()+'年'+(startTime.getMonth()+1)+'月'+startTime.getDate()+'日 '+startTime.getHours()+'时'+startTime.getMinutes()+'分'}开拍</p>
          <a href="javascript:;">开拍提醒我</a>
        </div>
      </div>
    );

    const nowAuction = (

      <div className="col-xs-12">
        <div className="time">
          <p className="now-auctioning-title">正在拍卖</p>
          <p className="time-left">剩余时间 : <span>{this.formatTime(remain)}</span></p>
        </div>
        <div id="progressBar">
          <div></div>
        </div>
        <div className="auction-avatar">

          {CallUserList}

        </div>

        {/* 出价器 */}
        <div className="auction-tools">
          <div className="col-xs-6">
            <p className="now-price"><div>当前最高</div> <div><span>{currentPrice}</span> <span></span></div> </p>
            <p className="add-input"><div>您的加价</div> <div><span>{priceInput}</span> <span></span> </div></p>
          </div>
          <div className="col-xs-6">
            {/* <p style={{ color : '#999' }}>快速加价</p> */}
            {/* <p></p> */}
            <div className="auc-btn-group">
              <button id="sub-btn" onClick={this.handleBtnSub}>-</button>
              <button id="add-btn" onClick={this.handleBtnAdd}>+</button>
            </div>
          </div>
              <div className="col-xs-6">
                <p className="your-price">
                  <b>您的出价 : </b>
                  <b>
                    <span>{currentPrice + priceInput}</span>
                    <span></span>
                  </b>
                </p>
              </div>
              <div className="col-xs-6">
                <button id="call-price" onClick={this.callPrice}>立即出价</button>
              </div>

        </div>
      </div>

    );

    const endAuction = (
      <div className="col-xs-12">
        <div className="time">
          <p className="now-auctioning-title">拍卖完结</p>
        </div>

        <div className="endAuction">
        <p>拍品已结束 !</p>
        {this.props.item.nickname?<p>恭喜{this.props.item.nickname}以<span>{this.props.item.price}</span>的价格拍得本拍品 !</p>:<p></p>}
        </div>
      </div>
    );

   const PayBond = (
     <div className="col-xs-12">
       <div className="time">
         <p className="now-auctioning-title">正在拍卖</p>
         <p className="time-left">剩余时间 : <span>{this.formatTime(remain)}</span></p>
       </div>
       <div id="progressBar">
         <div></div>
       </div>
       <div className="auction-avatar">
         {CallUserList}
       </div>
       <div className="auction-tools">
         <div className="col-xs-6">
           <p className="now-price"><div>当前出价</div> <div><span>{currentPrice}</span> <span></span></div> </p>
         </div>
         <div className="col-xs-6">
           <a
             className="join-auction" href={'/?g=Portal&m=Mpay&pid='+this.props.item.id+'&reffer='+encodeURIComponent(document.location.href)}>加入拍卖</a>
         </div>
       </div>
     </div>
   );

    let showAuction = this.props.item.auction_status == 0 ? readyAuction:
        this.props.item.auction_status != 1 ? endAuction:
        this.props.item.paid_bond == 0 ? PayBond:nowAuction;

    return (
      <div className="now-auction-block">
        {showAuction}
      </div>
    );
  }
}
export default NowAuction;
